package com.ctyon.watchmanager.ui.fragment;

import android.Manifest;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;

import com.ctyon.common.util.DataUtil;
import com.ctyon.common.util.TSnackbarUtil;
import com.ctyon.netlibrary.net.revert.BaseResponseEntity;
import com.ctyon.netlibrary.use.BaseObserver;
import com.ctyon.watchmanager.BasicApp;
import com.ctyon.watchmanager.R;
import com.ctyon.watchmanager.bean.ContactBean;
import com.ctyon.watchmanager.listener.ItemClickListener;
import com.ctyon.watchmanager.model.net.service.NetService;
import com.ctyon.watchmanager.ui.BaseFragment;
import com.ctyon.watchmanager.ui.adapter.ContactsImportAdapter;
import com.mcxtzhang.indexlib.IndexBar.widget.IndexBar;
import com.mcxtzhang.indexlib.IndexBar.widget.decoration.DividerItemDecoration;
import com.mcxtzhang.indexlib.suspension.SuspensionDecoration;
import com.orhanobut.logger.Logger;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;


/**
 * CreateDate：19-6-25 on 上午9:14
 * Describe:
 * Coder: lee
 */
public class ContactsImportFragment extends BaseFragment {

    public static final String TAG = "ContactsImportFragment";

    private ContactsImportAdapter mAdapter;
    private SuspensionDecoration mDecoration;
    private IndexBar mIndexBar;
    private View viewEmpty;
    private FrameLayout layoutImport;
    private Button btImport;

    private List<ContactBean> mList = new ArrayList<>();
    private List<ContactBean> contactList = new ArrayList<>();
    private List<ContactBean> importList = new ArrayList<>();

    public static ContactsImportFragment newInstance() {
        final ContactsImportFragment fragment = new ContactsImportFragment();
        final Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_contacts_import, container, false);

        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(RecyclerView.VERTICAL);
        RecyclerView recyclerView = view.findViewById(R.id.contacts_recycle);
        recyclerView.setLayoutManager(layoutManager);

        mAdapter = new ContactsImportAdapter(itemClickListener);
        recyclerView.setAdapter(mAdapter);

        recyclerView.addItemDecoration(mDecoration = new SuspensionDecoration(getActivity(), contactList));
        //如果add两个，那么按照先后顺序，依次渲染。
        recyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST));

        mIndexBar = view.findViewById(R.id.index_bar);
        mIndexBar.setmPressedShowTextView(view.findViewById(R.id.tv_bar_hint))//设置HintTextView
                .setNeedRealIndex(true)//设置需要真实的索引
                .setmLayoutManager(layoutManager);//设置RecyclerView的LayoutManager

        btImport = view.findViewById(R.id.bt_import);
        btImport.setOnClickListener(v -> uploadContacts());

        viewEmpty = view.findViewById(R.id.import_empty);
        layoutImport = view.findViewById(R.id.import_layout);

        return view;

    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        new RxPermissions(getActivity()).request(Manifest.permission.READ_CONTACTS)
                .subscribe(granted -> {
                    Logger.i("rxPermissions : granted = " + granted);
                    if (granted) { // Always true pre-M
                        queryContactPhoneNumber();
                    } else {
                        TSnackbarUtil.TSBError(getActivity(), "请打开通讯录权限");
                    }
                });

        loadContactsE();
    }

    private void loadContactsE(){
        BasicApp.getInstance().getAppExecutors().networkIO().execute(() -> {
            String contactsStr = BasicApp.getInstance().getWatch().getContacts();
            mList.clear();
            if (!DataUtil.isEmptyAnd(contactsStr) && contactsStr.contains("&")) {
                String[] strings = contactsStr.split("&");
                ContactBean contactBean = null;
                for (int i = 0; i < strings.length; i++) {
                    if (i % 2 == 0) {
                        contactBean = new ContactBean();
                        contactBean.setNumber(strings[i]);
                    } else {
                        contactBean.setName(DataUtil.unicode2String(strings[i]));
                        mList.add(contactBean);
                    }
                }
            }
        });
    }

    private final ItemClickListener<Integer> itemClickListener = (index) -> {
        Logger.d("id = " + index);
        if (mAdapter.setChecked(index)){
            importList.add(contactList.get(index));
        } else {
            if (importList.contains(contactList.get(index))){
                importList.remove(contactList.get(index));
            }
        }
        if (importList.size() > 0){
            btImport.setVisibility(View.VISIBLE);
        } else {
            btImport.setVisibility(View.GONE);
        }
    };

    private void queryContactPhoneNumber() {
        Observable.create((ObservableOnSubscribe<List<ContactBean>>) emitter -> {
            if (contactList.size() > 0) {
                contactList.clear();
            }
            if (importList.size() > 0) {
                importList.clear();
            }
            String[] cols = {ContactsContract.PhoneLookup.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER};
            Cursor cursor = getActivity().getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, cols, null, null, null);
            for (int i = 0; i < cursor.getCount(); i++) {
                cursor.moveToPosition(i);
                // 取得联系人
                int nameFieldColumnIndex = cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME);
                int numberFieldColumnIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
                String name = cursor.getString(nameFieldColumnIndex);
                String number = cursor.getString(numberFieldColumnIndex);
                Log.d("contact", "name = " + name + "  number = " + number);
                contactList.add(new ContactBean(name, number));
            }
            emitter.onNext(contactList);
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(list -> {
                    mIndexBar.setmSourceDatas(list);//设置数据.invalidate();
                    mDecoration.setmDatas(list);
                    mAdapter.setData(list);
                    if (list.size() == 0) {
                        viewEmpty.setVisibility(View.VISIBLE);
                        layoutImport.setVisibility(View.GONE);
                    } else if (list.size() < 10){
                        mIndexBar.setVisibility(View.GONE);
                    }
                });
    }

    private void uploadContacts() {
        if (importList.size() == 0) {
            TSnackbarUtil.TSBError(getActivity(), "无数据");
            return;
        }
        if (mList.size() + importList.size() > 5){
            TSnackbarUtil.TSBError(getActivity(), "最多只能保存5个联系人");
            return;
        }
        for (ContactBean contact : mList) {
            for (ContactBean c : importList) {
                if (contact.toString().equals(c.toString())){
                    TSnackbarUtil.TSBError(getActivity(), "重复添加： " + c.getName() + "已存在");
                    return;
                }
            }
        }

        final StringBuilder contactsData = new StringBuilder();
        mList.addAll(importList);
        Logger.t(LTAG).d("mList size = " + mList.size());
        for (int i = 0; i < mList.size(); i++) {
            if (i > 0) {
                contactsData.append("&");
            }
            contactsData.append(mList.get(i).toString());
        }
        String data = contactsData.toString().replace(" ", "");
        Logger.t(LTAG).d("contactsData : " + data);
        final String method = "contacts";
        if (NetService.getInstance().isDisable(method)) {
            TSnackbarUtil.TSBError(getActivity(), "请稍候...");
            return;
        }
        NetService.getInstance()
                .method(method)
                .contacts(BasicApp.getInstance().getManager().getManagerId(), BasicApp.getInstance().getWatch().getMeid(), data)
                .timeout(10, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<BaseResponseEntity>() {
                    @Override
                    public void onSuccess(BaseResponseEntity responseEntity) {
                        Logger.d("onSuccess : " + responseEntity.toString());
                        TSnackbarUtil.TSBSuccess(getActivity(), "导入成功");
                        BasicApp.getInstance().getWatch().setContacts(data);
                        getActivity().finish();
                    }

                    @Override
                    public String onOver() {
                        loadContactsE();
                        return method;
                    }

                });
    }

}
